package com.kpx.app.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.kpx.app.R;
import com.kpx.app.adapter.OrderAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.OrderBean;
import com.kpx.app.bean.OrderStatusMenuBean;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.uiutils.ToastUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * User: 陈聪(617909447@qq.com)
 * Date: 2016-06-23
 * Time: 09:58
 * FIXME
 */
public class ViewOrderShow extends LinearLayout {

    @BindView(R.id.txt_empty_mention2)
    TextView txtEmptyMention2;
    @BindView(R.id.ll_empty_mention)
    LinearLayout llEmptyMention;
    /**
     * 订单状态菜单对象
     */
    private OrderStatusMenuBean menuBean;
    /**
     * 上下拉刷新控件
     */
    private XRefreshView outView;
    /**
     * 订单列表
     */
    private ListView lv_order_show;
    /**
     * 当前页
     */
    private int pageNow = 1;
    /**
     * 每页加载数量
     */
    private int pageSize = 10;
    /**
     * 是否刷新操作
     */
    private boolean isRefresh;
    /**
     * 订单数据列表
     */
    private ArrayList<OrderBean> orderBeans = new ArrayList<>();
    /**
     * 订单列表适配器
     */
    private OrderAdapter adapter;
    /**
     * 上下文对象
     */
    private Context context;
    /**
     * 空提示
     */
    private TextView txt_empty_mention;
    private int totalPage;
    public static boolean toPosition = false;
    private int select;

    public ViewOrderShow(Context context) {
        super(context);
        initView(context);
    }

    public ViewOrderShow(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ViewOrderShow(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public ViewOrderShow(Context context, OrderStatusMenuBean menuBean) {
        super(context);
        this.menuBean = menuBean;
        initView(context);
    }

    private void initView(final Context context) {
        this.context = context;
        View view = View.inflate(context, R.layout.view_super_market_order_show, this);
        ButterKnife.bind(view);
        outView = (XRefreshView) view.findViewById(R.id.custom_view);
        txt_empty_mention = (TextView) view.findViewById(R.id.txt_empty_mention);
        lv_order_show = (ListView) view.findViewById(R.id.lv_order_show);
        initRefreshView();
        lv_order_show.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                select = lv_order_show.getFirstVisiblePosition();
                return false;
            }
        });
        txtEmptyMention2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)context).finish();
                ((ActivityBase)context).toSelectTab(1);
            }
        });
        //商品列表的上下拉刷新操作
        outView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                pageNow = 1;
                toPosition = false;
                getOrders();// 获取数据
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isRefresh = false;
                if (pageNow >= totalPage) {
                    ToastUtil.getInstance().showToast(context, "没有更多了");
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            outView.stopLoadMore();
                        }
                    }, 600);
                } else {
                    pageNow++;
                    toPosition = false;
                    getOrders();// 获取数据
                }
            }
        });
        adapter = new OrderAdapter(context, orderBeans, R.layout.item_order_show);
        lv_order_show.setAdapter(adapter);
        isRefresh = true;
        getOrders();
    }

    /**
     * 获取订单数据
     */
    private void getOrders() {
        ((ActivityBase) context).showLoadingDialog();
        MyHashMap map = new MyHashMap();
        if (menuBean.getStatus() != -1) {
            map.put("orderStatus", menuBean.getStatus() + "");
        }
        map.put("pageIndex", pageNow + "");
        map.put("pageSize", pageSize + "");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                ((ActivityBase) context).dissmissLoadingDialog();
                if (isRefresh) {
                    outView.stopRefresh();
                } else {
                    outView.stopLoadMore();
                }
                if (result.getCode() == 0 && result.getData() != null) {
                    ArrayList<OrderBean> getData = (ArrayList<OrderBean>) result.getData();
                    if (isRefresh) {
                        orderBeans.clear();
                        if (getData.size() == 0) {
                            txt_empty_mention.setText("暂无相关订单信息");
                            txt_empty_mention.setOnClickListener(null);
                            llEmptyMention.setVisibility(View.VISIBLE);
                        } else {
                            llEmptyMention.setVisibility(View.GONE);
                        }
                    } else {
                        if (getData.size() % pageSize != 0) {
                        }
                    }
                    totalPage = result.getPage().getPageSize();
                    outView.setAutoLoadMore(true);
                    outView.setPullRefreshEnable(true);
                    outView.setPullLoadEnable(true);
                    orderBeans.addAll(getData);
                    adapter.setData(orderBeans);
                    if (toPosition) {
                        lv_order_show.setSelection(select);
                    }
                } else {
                    tryagain(result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                ((ActivityBase) context).dissmissLoadingDialog();
                tryagain(error);
            }

        }, OrderBean.class, HttpDataRequest.TYPE_LIST).POST(menuBean.getStatus() == OrderBean.ORDER_STATUS_MY_GOODS ? HttpDataReqUrl.URL_POST_ORDER_MY_GOODS : HttpDataReqUrl.URL_POST_ORDER_LIST, true, map);
    }

    private void tryagain(String error) {
        if (isRefresh) {
            outView.stopRefresh();
            if (orderBeans.size() == 0) {
                llEmptyMention.setVisibility(View.VISIBLE);
                txt_empty_mention.setText("获取信息失败，点击重试");
                txt_empty_mention.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getOrders();// 获取数据
                    }
                });
            }
        } else {
            outView.stopLoadMore();
        }
        ToastUtil.getInstance().showToast(context, error);
    }


    /**
     * 初始化上下拉刷新
     */
    private void initRefreshView() {
        outView.setPullLoadEnable(true);
        outView.setPinnedTime(1000);
        outView.setAutoLoadMore(true);
//		outView.setCustomHeaderView(new CustomHeader(this));
//		outView.setCustomHeaderView(new XRefreshViewHeader(this));
        outView.setMoveForHorizontal(true);
//        outView.setCustomFooterView(new CustomerFooter(this));
//		outView.setPinnedContent(true);
    }

    /**
     * 根据订单状态bean对象进行数据刷新操作（根据订单状态首页刷新）
     *
     * @param statusMenuBean
     */
    public void setData(OrderStatusMenuBean statusMenuBean) {
        this.menuBean = statusMenuBean;
        pageNow = 1;
        orderBeans.clear();
        isRefresh = true;
        toPosition = false;
        getOrders();
    }

    /**
     * 订单列表数据刷新（首页刷新）
     */
    public void goReflush() {
        pageNow = 1;
        orderBeans.clear();
        isRefresh = true;
        toPosition = true;
        getOrders();
    }

    /**
     * 刷新数据（当前页数据刷新）
     */
    public void refreshData() {
//        if (orderBeans.size() == 0) {
        initRefreshView();
        goReflush();
//        }
    }

    /**
     * 刷新单条订单状态
     *
     * @param intent
     */
    public void reflushOrder(Intent intent) {
        String orderId = intent.getStringExtra(context.getResources().getString(R.string.intent_key_id));
        int status = intent.getIntExtra(context.getResources().getString(R.string.intent_key_status), 0);
        if (TextUtils.isEmpty(orderId)) return;
        for (int i = 0; i < orderBeans.size(); i++) {
//            if (orderId.equals(orderBeans.get(i).getOrderStringID())) {
//                orderBeans.get(i).setOrderStatus(status);
//                adapter.setData(orderBeans);
//            }
        }
    }
}
